
package com.neuedu.my12306.dao;
/**
 * 设计一个jdbc操作工具类，用于封装通用操作
 * @author admin
 *
 */

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;




public class DBHelper {
	//封装4个参数
	private static final String DRIVER= "oracle.jdbc.driver.OracleDriver";
	private static final String URL = "jdbc:oracle:thin://localhost:1521/orcl";
	private static final String USER= "my12306user";
	private static final String PASSWORD= "123456";
	
	// 1.注册驱动 2.建立连接
		public static Connection openConnection() {
			Connection conn = null;
			// 查询tomcat服务器是否配置了连接池，
			try {
				//得到JNDI上下文环境
				Context ctx = new InitialContext(); 
				//通过JNDI查询可用的服务：参数java：/comp/env为固定路径
				//Context envContext = (Context)ctx.lookup("java:/comp/env");
				//参数jdbc/webdb为数据源和JNDI绑定
				DataSource dataSource = (DataSource) ctx.lookup("java:/comp/env/jdbc/webdb");
				conn = dataSource.getConnection();
			} catch (NamingException e1) {
				e1.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				if(conn!=null) {
					System.out.println("通过连接池获取到数据库连接");
				}else {
					Class.forName(DRIVER);
					conn = DriverManager.getConnection(URL, USER, PASSWORD);
					System.out.println("使用连接池获取连接失败，重新使用JDBC获取数据库连接！");
				}	
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			return conn;
		}
	//6.关闭连接，释放资源
		public static void closeAll(ResultSet rs,Statement stmt,Connection conn) {
			//这个一个标准的关闭动作
			if(rs!=null) {
				try {
					rs.close();
				} catch (SQLException e) {
				}
			}
			if(stmt!=null) {
				try {
					stmt.close();
				} catch (SQLException e) {
				}
			}
			
			if(conn!=null) {
				try {
					conn.close();
				} catch (SQLException e) {
				}
			}
		}
}
